"""
Author : Mr.Sun
DateTime : 2022/10/21.13:53
FileName : APSchedulerMain.py
Desc :
"""
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from core.Political import current_affairs_generate
from core.RecruitAction import position_together
from core.EmailUtil import do_work
from utils.logger import logger
from core.OperateSqlite import project_dir

jobstores = {
    'default': SQLAlchemyJobStore(url='sqlite:///' + project_dir + '/data.db')
}


def my_listener(event):
    if event.exception:
        logger.error('apscheduler exec error ' + str(event.exception))


def apscheduler_work():
    try:
        scheduler = BlockingScheduler(jobstores=jobstores)
        scheduler.add_job(func=current_affairs_generate,
                          args=('https://www.chinagwy.org/html/ggjczs/mszt/202201/52_469149.html',),
                          trigger='cron',
                          hour=16,
                          minute=30,
                          id='current_affairs_generate',
                          replace_existing=True)
        scheduler.add_job(func=do_work,
                          trigger='cron',
                          hour=18,
                          minute=30,
                          id='send_email_work',
                          replace_existing=True)
        scheduler.add_job(func=position_together,
                          args=(10,),
                          trigger='cron',
                          minute=15,
                          id='position_together',
                          replace_existing=True)

        scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
        scheduler._logger = logger
        scheduler.start()
    except Exception as e:
        logger.error("Exception is " + str(e))


if __name__ == '__main__':
    apscheduler_work()
